import { Controller } from 'egg';
import { Op } from 'sequelize';

export default class GoodsController extends Controller {


  // 轮播图列表
  async list() {
    const { page, pageSize, ...where } = this.ctx.validateReq(
      'pic.carousel.list',
    ).query;

    const result = await this.ctx.service.pic.carousel.index(page, pageSize, where);

    if (result) {
      this.ctx.success({
        data: result
      });
    }
  }

  async getBannersForTemplate() {

    const { ids } = this.ctx.validateReq(
      'pic.carousel.forTpl',
    ).query;
    const pids = ids.split(',')
    const data = await this.ctx.model.Ad.findAll({
      where: {
        id: {
          [Op.in]: pids
        },
      },
      raw: true
    })


    this.ctx.success({
      data: data
    })
  }



  // 新建轮播图
  async create() {
    const { body } = this.ctx.validateReq('pic.carousel.create');

    const isExist = await this.ctx.model.Ad.findOne({
      where: {
        name: body.name,
      }
    });

    if (isExist) {
      return this.ctx.failure({
        code: 30000,
        data: {
          name: body.name,
        },
      });
    }

    const result = await this.ctx.service.pic.carousel.create(body);

    if (result) {
      this.ctx.success({
        data: {
          id: result.id,
        },
        status: 201,
      });
    }
  }


  // 编辑轮播图
  async update() {

    const { body, params: { id } } = this.ctx.validateReq('pic.carousel.update');

    const isExist = await this.ctx.model.Ad.findOne({
      where: {
        id: { [Op.ne]: id },
        name: body.name,
      }
    });

    if (isExist) {
      return this.ctx.failure({
        code: 30010,
        data: {
          name: body.name,
        },
      });
    }

    const result = await this.ctx.service.pic.carousel.update(id, body);

    if (result) {
      this.ctx.success({
        data: {
          id: result.id,
        }
      });
    }
  }


  // 删除轮播图
  async destroy() {
    const { params: { id } } = this.ctx.validateReq('pic.carousel.destroy');

    const result = await this.ctx.service.pic.carousel.destroy(id);

    if (result) {
      this.ctx.success({
        data: {
          id: result.id,
        }
      });
    }
  }

}
